const { Op } = require("sequelize");
const Message = require("./models/Message");
const Blog = require("./models/Blog");

exports.addMessage = async (info) => {
    if (info.blogId) {
        const blogIns = await Blog.findByPk(info.blogId);
        blogIns.commentNumber++;
        await blogIns.save();
    }
    const ins = await Message.create(info);
    return ins.toJSON();
}

exports.getMessages = async (page, limit, blodId, token) => {
    const where = {};
    const include = [];
    const order = [];
    if (blodId === -1) {
        // 获取留言板的评论
        console.log("获取留言");
        where.blogId = null;
        order.push(["createDate", "desc"]);
    } else {
        // 获取文章评论的评论
        if (!token) {
            // 前台
            console.log("前台获取评论");
            where.blogId = blodId;
            order.push(["createDate", "desc"]);
        } else {
            // 后台
            console.log("后台获取评论");
            where.blogId = {
                [Op.ne]: null
            };
            include.push({
                model: Blog,
                as: "blog"
            });
        }
    }
    const res = await Message.findAndCountAll({
        include,
        where,
        order,
        offset: (page - 1) * limit,
        limit
    });
    return {
        total: res.count,
        rows: JSON.parse(JSON.stringify(res.rows))
    }
}

exports.deleteMessage = async (id) => {
    const ins = await Message.findByPk(id);
    if (ins.blogId) {
        const blogIns = await Blog.findByPk(ins.blogId);
        blogIns.commentNumber--;
        await blogIns.save();
    }
    return await ins.destroy();
}

exports.deleteMessageByBlogId = async (blogId) => {
    const count = await Message.count();
    const blogIns = await Blog.findByPk(blogId);
    blogIns.commentNumber - count;
    await blogIns.save();
    return await Message.destroy({
        where: {
            blogId
        }
    });
}
